<template>
  <view class="page">
    <u-form
      :model="pageForm"
      ref="formRef"
      label-position="top"
      :border-bottom="false"
      :label-style="labelStyle"
      :placeholder-style="placeholderStyle"
    >
      <u-form-item label="品牌类型" prop="brandType">
        <u-input
          v-model="brandTypeDisplayValue"
          type="select"
          @click="showBrandTypeSelect = true"
          :select-open="showBrandTypeSelect"
          :border="true"
          :border-color="borderColor"
          placeholder="请选择品牌类型"
        />
        <u-select
          v-model="showBrandTypeSelect"
          mode="single-column"
          :list="brandTypeOptions"
          label-name="label"
          value-name="value"
          @confirm="brandTypeSelectSelect"
          :defaultValue="[currentbrandTypeSelectIndex]"
        >
        </u-select>
      </u-form-item>
      <u-form-item label="品牌名称" prop="brandName"
        ><u-input v-model="pageForm.brandName" border :border-color="borderColor" placeholder="请输入名称"
      /></u-form-item>
      <u-form-item label="品牌标题" prop="brandTitle"
        ><u-input v-model="pageForm.brandTitle" border :border-color="borderColor" placeholder="请输入标题"
      /></u-form-item>
      <u-form-item label="品牌简介" prop="brandIntroduction"
        ><u-input v-model="pageForm.brandIntroduction" border :border-color="borderColor" placeholder="请输入简介"
      /></u-form-item>

      <u-form-item label="品牌logo">
        <u-upload
          ref="upload1"
          :auto-upload="false"
          max-count="1"
          :action="UPLOAD_URL"
          :file-list="fileList1"
          :customBtn="true"
          width="145rpx"
          height="145rpx"
          @on-list-change="handleListChange"
          @on-uploaded="onUploaded1"
          :header="uploadHeader"
        >
          <template v-slot:addBtn>
            <image class="upload_hover_bg" src="/static/upload_hover_bg.png" mode="aspectFill"></image>
          </template>
        </u-upload>
      </u-form-item>

      <u-form-item label="品牌图片(16：9)">
        <u-upload
          ref="upload2"
          :auto-upload="false"
          max-count="3"
          :action="UPLOAD_URL"
          :file-list="fileList2"
          :customBtn="true"
          width="145rpx"
          height="145rpx"
          @on-list-change="handleListChange2"
          @on-uploaded="onUploaded2"
          :header="uploadHeader"
        >
          <template v-slot:addBtn>
            <image class="upload_hover_bg" src="/static/upload_hover_bg.png" mode="aspectFill"></image>
          </template>
        </u-upload>
      </u-form-item>

      <u-form-item label="品牌备用核销账号（仅支持手机号）">
        <view class="backup_phones" v-for="(item, index) in pageForm.standbyVerifyAccount">
          <u-input
            v-model="item.value"
            border
            :border-color="borderColor"
            placeholder="请输入手机号"
            :custom-style="customStyle"
          />
          <image
            v-if="index == pageForm.standbyVerifyAccount.length - 1"
            class="add_btn"
            src="/static/form/add2.png"
            mode="aspectFill"
            @click="handlePhoneAdd"
          ></image>
          <image
            v-else
            class="add_btn"
            src="/static/form/minus.png"
            mode="aspectFill"
            @click="handlePhoneMinus(index)"
          ></image>
        </view>
      </u-form-item>

      <!-- 营业执照上传  -->
      <view class="upload_box">
        <u-upload
          width="100%"
          height="calc((100vw - 80rpx) * 0.4414)"
          ref="upload3"
          :auto-upload="false"
          max-count="1"
          :action="UPLOAD_URL"
          :file-list="fileList3"
          :customBtn="true"
          @on-uploaded="onUploaded3"
          :header="uploadHeader"
        >
          <template v-slot:addBtn>
            <view class="hover_box">
              <image class="img" src="/static/form/add.png" mode="aspectFill"></image>
            </view>
          </template>
        </u-upload>
      </view>

      <view class="upload_tip">请上传营业执照/品牌授权书</view>
    </u-form>

    <view class="create_btn" @click="createShop">创建店铺</view>
    <div class="created_list" v-if="formStore.shopList && formStore.shopList.length > 0">
      <div class="item" v-for="item in formStore.shopList">{{ item.shopName }}</div>
    </div>

    <view class="submit" @click="submit">提交审核</view>
    <view class="safe_area" :style="{ height: '80rpx' }"></view>
  </view>
</template>

<script setup>
  import { ref, reactive, computed } from 'vue';
  import { onShow, onLoad } from '@dcloudio/uni-app';
  import { UPLOAD_URL } from '../../config/config';
  import { useFormStore } from '../../store/form';
  import { useUserStore } from '../../store/user';
  import { addBrand } from '../../apis/pages';

  const userStore = useUserStore();
  const formStore = useFormStore();

  const borderColor = '#747474';

  const customStyle = {
    width: 'calc(100vw - 200rpx)',
  };

  const pageForm = reactive({
    brandType: '', // 品牌类型
    brandName: '',
    brandTitle: '',
    brandIntroduction: '',
    standbyVerifyAccount: [{ value: '' }], //备用手机号
  });

  const uploadForm = reactive({
    brandLogoImage: '', //logo图
    brandImage: '', //品牌图
    brandInfoImage: '', //营业执照
  });

  // 三个上传完成标志
  const uploadStatus = reactive({
    brandLogoImageUploaded: false,
    brandImageUploaded: false,
    brandInfoImageUploaded: false,
  });

  const isSubmit = ref(false);

  // 上传相关
  const upload1 = ref();
  const upload2 = ref();
  const upload3 = ref();
  const uploadHeader = {
    authorization: 'Bearer ' + userStore.token,
  };

  // 图片1 是否上传了
  const isImgUploaded1 = ref(false);
  const fileList1 = ref([]);

  const isImgUploaded2 = ref(false);
  const fileList2 = ref([]);

  const fileList3 = ref([]);

  // form 样式相关

  const labelStyle = {
    'font-weight': 600,
    'font-size': '30rpx',
    color: '#1E2737',
    // width: '100%',
  };

  const placeholderStyle = {
    'font-weight': 500,
    'font-size': '26rpx',
    color: '#989898',
  };

  const verifyLabelStyle = {
    'font-weight': 500,
    'font-size': '26rpx',
    color: '#989898',
  };

  // 归属select
  const showBrandTypeSelect = ref(false);
  const brandTypeDisplayValue = ref('');
  const currentbrandTypeSelectIndex = ref(0);
  const brandTypeOptions = [
    {
      label: '普通商家品牌',
      value: '1',
    },
    {
      label: '营业厅专用品牌',
      value: '2',
    },
  ];

  onShow(() => {
    console.log(formStore.brandForm, 'formStore.brandForm ?>>>>');

    console.log(formStore.shopList, 'shopList>>');
  });

  onLoad(() => {
    console.log('onLoad');
  });

  function resetUploadStatus() {
    uploadStatus.brandLogoImageUploaded = false;
    uploadStatus.brandImageUploaded = false;
    uploadStatus.brandInfoImageUploaded = false;
  }

  function brandTypeSelectSelect(e) {
    pageForm.brandType = e[0].value;
    showBrandTypeSelect.value = false;
    currentbrandTypeSelectIndex.value = e[0].index;
    brandTypeDisplayValue.value = e[0].label;
  }

  // 上传组件本地图片列表变化
  function handleListChange(n) {
    if (upload1.value.lists.length > 0) {
      isImgUploaded1.value = true;
    } else {
      isImgUploaded1.value = false;
    }
  }

  function handleListChange2(n) {
    if (upload2.value.lists.length > 0) {
      isImgUploaded2.value = true;
    } else {
      isImgUploaded2.value = false;
    }
  }

  function onUploaded1(list) {
    uploadForm.brandLogoImage = list[0].response.data;
    uploadStatus.brandLogoImageUploaded = true;
    checkAllUploaded();
  }

  function onUploaded2(list) {
    console.log(list, 'list>>>');

    // uploadForm.brandImage = list[0].response.data;
    uploadForm.brandImage = list
      .map((item) => {
        return item.response.data;
      })
      .join(',');

    console.log(uploadForm.brandImage, ' brandImage >>>>');
    uploadStatus.brandImageUploaded = true;
    checkAllUploaded();
  }

  function onUploaded3(list) {
    uploadForm.brandInfoImage = list[0].response.data;
    uploadStatus.brandInfoImageUploaded = true;
    checkAllUploaded();
  }

  // 检查是否全部上传完
  function checkAllUploaded() {
    const allUploaded = Object.values(uploadStatus).every((status) => status);

    if (allUploaded) {
      isSubmit.value = false;
      resetUploadStatus();
      uni.hideLoading();
      // 合并表单
      mergeForm();
    }
  }

  // 合并表单
  function mergeForm() {
    console.log('brand  所有图片上传成功，可以合并数据了');

    formStore.brandForm = {
      ...formStore.brandForm,
      ...pageForm,
      ...uploadForm,
      standbyVerifyAccount: pageForm.standbyVerifyAccount.map((item) => item.value).join(','), // 处理核销手机号
    };

    // * 创建店铺
    if (isCreateNew.value) {
      let timpstamp = new Date().getTime();
      formStore.currentShopId = timpstamp; // 记录当前操作的shopid
      formStore.brandForm.shopList.push({
        sid: timpstamp, // 前端使用的商铺 id
      });
      isCreateNew.value = false;
      console.log('当前brand：', formStore.brandForm);

      uni.navigateTo({
        url: '/pagesB/shop/index?from=form',
      });
    } else {
      // * 审核按钮
      formStore.brandForm.merchantId = uni.getStorageSync('merchantId');
      console.log('最终提交的数据：', formStore.brandForm);

      addBrand(formStore.brandForm).then((res) => {
        console.log(res, 'res >>>');
        if (res.code == 200) {
          formStore.resetBrandForm();
          uni.reLaunch({ url: '/pagesB/register/finish' });
        } else {
          uni.showToast({
            title: res.message,
            icon: 'none',
          });
        }
      });
    }
  }

  // 增加备用手机号(4)
  function handlePhoneAdd() {
    if (pageForm.standbyVerifyAccount.length == 4) {
      uni.showToast({
        title: '最多添加4个',
        icon: 'none',
      });
    } else {
      pageForm.standbyVerifyAccount.push({
        value: '',
      });
    }
  }

  // 减少备用手机号
  function handlePhoneMinus(index) {
    pageForm.standbyVerifyAccount.splice(index, 1);
  }
  const isCreateNew = ref(false);
  function createShop() {
    isCreateNew.value = true;
    submit();
  }

  function submit() {
    if (isSubmit.value) return;
    console.log(pageForm, 'pageForm >>>');

    if (upload1.value.lists.length && upload2.value.lists.length && upload3.value.lists.length) {
      isSubmit.value = true;
      uni.showLoading({
        title: '提交中...',
        mask: true,
      });
      upload1.value.upload();
      upload2.value.upload();
      upload3.value.upload();
    } else {
      mergeForm();
    }
  }
</script>

<style scoped lang="scss">
  // /deep/ .u-form-item {
  //   padding-bottom: 0 !important;
  // }

  .page {
    width: 100vw;
    min-height: 100vh;
    padding: 40rpx;
    box-sizing: border-box;
    font-size: 28rpx;
    background-color: #f5f5f5;
  }

  .upload_hover_bg {
    width: 145rpx;
    height: 145rpx;
    vertical-align: middle;
  }

  .content {
    background-color: #fff;
    padding: 20rpx;
    border-radius: 16rpx;
    box-sizing: border-box;
    margin-bottom: 30rpx;
  }

  .label_title {
    font-weight: 600;
    font-size: 30rpx;
    color: #1e2737;
    margin-bottom: 30rpx;
  }

  .verify_form {
    padding: 0 20rpx;
  }

  .upload_box {
    margin-bottom: 20rpx;
  }

  .hover_box {
    display: flex;
    align-items: center;
    justify-content: center;
    width: calc(100vw - 80rpx);
    height: calc((100vw - 80rpx) * 0.4414);
    background-color: #e5e5e5;
    border-radius: 20rpx;
    overflow: hidden;

    .img {
      width: 102rpx;
      height: 102rpx;
    }
  }

  .upload_tip {
    font-weight: 500;
    font-size: 26rpx;
    color: #989898;
    text-align: center;
    margin-bottom: 40rpx;
  }

  .create_btn {
    width: 188rpx;
    height: 67rpx;
    border: 2rpx solid #4287f6;
    text-align: center;
    line-height: 67rpx;
    box-sizing: border-box;
    font-weight: 500;
    font-size: 27rpx;
    color: #4287f6;
    border-radius: 40rpx;
    margin-bottom: 32rpx;
  }

  .created_list {
    margin-bottom: 40rpx;

    .item {
      font-weight: 600;
      font-size: 30rpx;
      color: #1e2737;
      border-bottom: 2rpx solid #e5e5e5;
      padding-left: 4rpx;
      padding-bottom: 12rpx;
      margin-bottom: 16rpx;
    }
  }

  .submit {
    width: 537rpx;
    height: 83rpx;
    background: #016bec;
    border-radius: 10rpx;

    font-weight: 500;
    font-size: 30rpx;
    color: #ffffff;

    text-align: center;
    line-height: 83rpx;
    margin: 0 auto;
  }

  .backup_phones {
    display: flex;
    align-items: center;
    margin-bottom: 10rpx;

    .add_btn {
      width: 64rpx;
      min-width: 64rpx;
      height: 64rpx;
      margin-left: 12rpx;
    }
  }
</style>
